package com.alibaba.sample.petstore.biz.admin.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.fileupload.FileItem;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.dao.DataIntegrityViolationException;

import com.alibaba.common.lang.io.StreamUtil;
import com.alibaba.sample.petstore.biz.admin.AdminManager;
import com.alibaba.sample.petstore.biz.admin.AdminManagerException;
import com.alibaba.sample.petstore.biz.admin.DuplicatedProductException;
import com.alibaba.sample.petstore.dal.dao.CategoryDao;
import com.alibaba.sample.petstore.dal.dao.ProductDao;
import com.alibaba.sample.petstore.dal.dataobject.Category;
import com.alibaba.sample.petstore.dal.dataobject.Product;

public class AdminManagerImpl implements AdminManager, ResourceLoaderAware {
    private ResourceLoader resourceLoader;
    private CategoryDao categoryDao;
    private ProductDao productDao;

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public void setCategoryDao(CategoryDao categoryDao) {
        this.categoryDao = categoryDao;
    }

    public void setProductDao(ProductDao productDao) {
        this.productDao = productDao;
    }

    public Category getCategory(String categoryId) {
        return categoryDao.getCategoryById(categoryId);
    }

    public void addProduct(Product product, String categoryId, FileItem picture) throws AdminManagerException {
        String imageFileName;

        try {
            imageFileName = getPictureName(picture);
        } catch (IOException e) {
            throw new AdminManagerException(e);
        }

        product.setLogo(imageFileName);
        product.setCategoryId(categoryId);

        try {
            productDao.insertProduct(product);
        } catch (DataIntegrityViolationException e) {
            throw new DuplicatedProductException(product.getProductId());
        }
    }

    private String getPictureName(FileItem picture) throws IOException {
        File uploadDir = resourceLoader.getResource("/petstore/upload").getFile();

        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        if (!uploadDir.isDirectory()) {
            throw new IOException("Could not create directory " + uploadDir.getAbsolutePath());
        }

        String imageFileName = null;

        if (picture != null) {
            String fileName = picture.getName().replace('\\', '/');

            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);

            String ext = "";
            int index = fileName.lastIndexOf(".");

            if (index > 0) {
                ext = fileName.substring(index);
            }

            InputStream is = null;
            OutputStream os = null;

            try {
                File imageFile = File.createTempFile("image_", ext, uploadDir);

                imageFileName = imageFile.getName();

                is = picture.getInputStream();
                os = new BufferedOutputStream(new FileOutputStream(imageFile));

                StreamUtil.io(is, os);
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                    }
                }

                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

        return imageFileName;
    }
}
